package com.common.rabbitmq.producer;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public abstract class AbstractProducer implements Producer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public abstract String getExchange();
    public abstract String getDeadLetterExchange();
    public <T> void send(String routingKey, T message) {
        send(getExchange(), routingKey, message);
    }
    @Override
    public <T> void send(String exchange, String routingKey, T message){
        log.debug("发送消息 exchange：{} routingKey：{}，message：{}",exchange, routingKey, message);
        rabbitTemplate.convertAndSend(exchange,routingKey,message);
    }

    public <T> void sendDelay(String routingKey, T message, long delay) {
        sendDelay(getDeadLetterExchange(), routingKey, message, delay);
    }

    @Override
    public <T> void sendDelay(String exchange,  String routingKey, T message, long delay) {
        log.debug("发送延迟消息 exchange：{} routingKey：{}，message：{}",exchange, routingKey, message);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, message1 -> {
            MessageProperties properties = message1.getMessageProperties();
            properties.setExpiration(String.valueOf(delay));  // **setExpiration** 单位为毫秒
            return message1;
        });
    }
}
